<?php
/**
 * Created by PhpStorm.
 * User: 123
 * Date: 2020/7/6
 * Time: 13:21
 */

namespace app\service;


use think\Db;
use think\view\driver\Think;

class RankingService
{

    /**
     * 列表条件
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年7月6日13:23:24
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
    public static function RankingListWhere($params = [])
    {
        $data_params=[];
        if($params['category']==1)
        {
            //团队排行
            $data_params = [
                'table'             =>'team',
                'field'           =>'title,team_earnings,id,is_fake,team_num team_numbers',
                'page'			  => true,
                'number'	         => 10,
                'order'              =>'team_earnings desc',
                'total_num'           =>true,
            ];
        }elseif ($params['category']==2){
            //积分排行
            $data_params = [
                'table'             =>'member_property',
                'field'           =>'integral',
                'where'				=> [],
                'page'			  => true,
                'number'	         => 10,
                'order'              =>'integral desc',
                'total_num'           =>true,
            ];
        }elseif ($params['category']==3){
            //收益排行
            $data_params = [
                'table'             =>'member_property',
                'field'           =>'income',
                'where'				=> [],
                'page'			  => true,
                'number'	         => 10,
                'order'              =>'income desc',
                'total_num'           =>true,
            ];
        }elseif ($params['category']==4){
            //材料排行
            $data_params = [
                'table'             =>'member_property',
                'field'           =>'materials',
                'where'				=> [],
                'page'			  => true,
                'number'	         => 10,
                'order'              =>'materials desc',
                'total_num'           =>true,
            ];
        }

        if($params['category']!=1)
        {
            $data_params['field']= $data_params['field'].',member_code,member.name,member.head_portrait,is_fake,thumb,nickname,member_property.id fake_id';
        }

        $data_params['whereor']=[];

        return $data_params;
    }


    /**
     * 总数
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年6月28日09:56:02
     * @desc    description
     * @param    [array]          $where [条件]
     */
    public static function RankingTotal($params)
    {


//        if($params['category']==1)
//        {
            $where = empty($params['where']) ? [['id','>',0]] : $params['where'];
            $ranking_real=Db::name($params['table'])->where($where)->count();
//        }else{
//            $where = empty($params['where']) ? $params['where'] : $params['where'];
//            $ranking_real=Db::name('member')->leftJoin($params['table'],'member.code='.$params['table'].'.member_code')
//                ->where($where)
////                ->whereOr($params['whereor'])
//                ->count();
//        }
        return $ranking_real;
    }


    /**
     * 获取排行列表
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年6月28日09:56:02
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
    public static function RankingList($params)
    {

        $where = empty($params['where']) ? [['id','>',0]] : $params['where'];
        $page = $params['page'] ? true : false;
        $number = isset($params['number']) ? intval($params['number']) : 10;
        $field = empty($params['field']) ? '*' : $params['field'];
        $m = isset($params['m']) ? intval($params['m']) : 0;
        $n = isset($params['n']) ? intval($params['n']) : 10;
        $order = isset($params['order']) ? $params['order'] : $params['table'].'.id desc';


        // 获取列表
        if($params['category']==1)
        {

            $data = Db::name($params['table'])->where($where)->field($field)->order($order);

        }else{
            $where = empty($params['where']) ? $params['where'] : $params['where'];
            $data =  Db::name($params['table'])->leftJoin('member','member.code='.$params['table'].'.member_code')->where($where)->whereOr($params['whereor'])->field($field)->order($order);


        }

        //分页
        $page_html=null;
        if($page)
        {
            $data=$data->paginate($number, false, ['query' => request()->param()]);

            // $page_html=$data->render();

            $data=$data->toArray()['data'];

        }else{
            $data=$data->limit($m, $n)->select();
        }


        //$params['page_html']=$page_html;
        return self::InforDataDealWith($data,$params);


    }

    /**
     * 排行数据处理
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年6月28日09:56:02
     * @desc    description
     * @param   [array]          $data [原始数据]
     * @param   [array]          $params [输入参数]
     */
    public static function InforDataDealWith($data,$params){

        if(!empty($data))
        {

            foreach($data as $k=>&$v)
            {

                //名称 玩家id 数量 名次 类型
                //所属分类
                //$rank_num=$k+1;
                $rank_num=input('post.')['page']*input('post.')['limit']-input('post.')['limit']+$k+1;
               // dump($rank_num);exit;



                    switch (intval($params['category'])){
                        case 1:
                            $v['category']='团队';
                            $v['nickname']=$v['title'];
                            $v['fake_id']=$v['id'];
                            $v['numbers']=$v['team_earnings'];
                            $v['ranking_num']=$rank_num;
                            unset($v['title']);
                            unset($v['team_earnings']);
                            break;
                        case 2:

                            $v['category']='积分';
                            $v['numbers']=$v['integral'];
                            unset($v['integral']);
                            break;
                        case 3:
                            $v['category']='收益';
                            $v['numbers']=$v['income'];
                            unset($v['income']);
                            break;
                        case 4:
                            $v['category']='材料';
                            $v['numbers']=$v['materials'];
                            unset($v['integral']);
                            break;
                    }
                    if($params['category']!=1)
                    {
                        $v['nickname']=empty($v['name']) ? $v['nickname'] :$v['name'];
                        $v['ranking_num']=$rank_num;
                        $v['thumb']=empty($v['head_portrait']) ? $v['thumb'] :$v['head_portrait'];
                           unset($v['name']);
                           unset($v['head_portrait']);

                    }

                $v['cate']=$params['category'];


                // 图片
                if(isset($v['thumb']))
                {

                    if(!empty($v['thumb']))
                    {
                        $img = ResourceService::AttachmentPathViewHandle($v['thumb'],true);
                        file_exists(ROOT_PATH.$img);

                        $v['thumb'] = file_exists(ROOT_PATH.$img)?$img:false;
                    }
                }

            }
           // dump($data);exit;
        }else{
            return DataReturn('未获取到数据',-1,$data);
        }

        return DataReturn('获取成功',0,$data);


    }

    /**
     * 排行保存
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年6月28日09:56:02
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
    public static function RankingSave($params = [])
    {
        //数据校验
        $re_check=self::RankingCheck($params);
        $table=isset($re_check['table'])? $re_check['table'] : [];
        //字段整理
        $data=self::HandleData($params);
       // dump($data);exit;
        // 添加/编辑
        if (empty($params['id'])) {
            $data['is_fake']=2;
            $ranking_id = Db::name($table)->insertGetId($data);
            if (!$ranking_id)
            {
                throw new \BaseException(['code'=>403 ,'errorCode'=>'40000','msg'=>'添加排行失败','status'=>false,'debug'=>false]);
            }
        } else {
            $re = Db::name($table)->where(['id' => intval($params['id'])])->update($data);
            if (!$re)
            {
                throw new \BaseException(['code'=>403 ,'errorCode'=>'40009','msg'=>'修改排行失败','status'=>false,'debug'=>false]);

            }

        }

        return true;
    }

    /**
     * 数据校验
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年7月13日13:35:45
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
    public static function RankingCheck($params)
    {
        // 数据校验
        $p = [
            [
                'checked_type' => 'empty',
                'key_name' => 'nickname',
                'error_msg' => '名称不能为空',
                'error_code' => 40002,
            ],

            [
                'checked_type' => 'empty',
                'key_name' => 'numbers',
                'error_msg' => '数值不能为空',
                'error_code' => 40004,
            ],

        ];
        //创建插入数据
        $table='member_property';
        $filed='nickname';
        if ($params['category']!=1)
        {
            $p[]= [
                'checked_type' => 'empty',
                'key_name' => 'thumb',
                'error_msg' => '头像不能为空',
                'error_code' => 40003,
            ];
            //名称重复判断
//            $check_data = [
//                'where' => [['name', '=', $params['nickname']]],
//                'table' => 'member',
//                'msg' => '名称不能重复', 'error_code' => 40005,
//                'params'=>$params
//            ];
//            IndustryService::CheckTitle($check_data);
        }else{
            $table='team';
            $filed='title';
        }

        // 添加是判断标题是否重复
        $ret = ParamsChecked($params, $p);
        if(true !== $ret)
        {
            $error_arr = explode(',', $ret);
            throw new \BaseException(['code'=>403 ,'errorCode'=>$error_arr[1],'msg'=>$error_arr[0],'status'=>false,'debug'=>false]);
        }
//        $check_data = [
//            'where' => [[$filed, '=', $params['nickname']]],
//            'table' => $table,
//            'msg' => '名称不能重复', 'error_code' => 40005,
//            'params'=>$params
//        ];
//        IndustryService::CheckTitle($check_data);
        $re=['table'=>$table,];
        return $re;
    }

    /**
     * 数据整理
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年7月13日13:35:45
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
    public static function HandleData($params)
    {
        $data=[];
        if($params['category']==1)
        {
            $data['title']=$params['nickname'];
            $data['team_earnings']=$params['numbers'];
            $data['team_num']=$params['team_numbers'];
//            $table='team';
        }
        else{
            switch ($params['category'])
            {
                case 2:
                    $data['integral']=$params['numbers'];
                    break;
                case 3:
                    $data['income']=$params['numbers'];
                    break;
                case 4:
                    $data['materials']=$params['numbers'];
                    break;
            }
            $data['thumb']=str_replace('/upload/','',$params['thumb']);
            $data['nickname']=$params['nickname'];
        }

        return $data;
    }

    /**
     * 数据删除
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年7月13日13:35:45
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
    public static function DoDel($param){
        $id = $param['id'];
        $table= $param['type']==1 ? 'team' : 'member_property';
        $where_del = ['id' => $id];

        $re = Db::name($table)->where($where_del);
        $is_fake=$re->field('is_fake')->find();


        if($is_fake['is_fake']==1)
        {
            throw new \BaseException(['code'=>403 ,'errorCode'=>'40008','msg'=>'该对象为真实数据无法删除','status'=>false,'debug'=>false]);
        }
        $del=Db::name($table)->where($where_del)->delete();

        if (!$del)
        {
            throw new \BaseException(['code'=>403 ,'errorCode'=>'40007','msg'=>'删除排行失败','status'=>false,'debug'=>false]);
        }
        return true;
    }
}